package com.dinner.util;

import java.sql.Connection;
import java.sql.SQLException;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import static java.sql.Connection.*;

public class TransactionInterceptor extends HibernateDaoSupport {

	protected TransactionState doBeforeTransaction() {
		SessionFactory sessionFactory = getSessionFactory();
		Session session = sessionFactory.openSession();
		
		Connection connection = session.connection();
		int oldValue;
		try {
			oldValue = connection.getTransactionIsolation();
			connection.setTransactionIsolation(TRANSACTION_SERIALIZABLE);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		
		session.beginTransaction();
		return new TransactionState(session, oldValue);
	}
	
	protected void doAfterTransaction(Session session, int oldValue) 
		throws HibernateException, SQLException {
		session.getTransaction().commit();
		session.connection().setTransactionIsolation(oldValue);
	}
}


